/**
 * (C) 2007 - 2009 Parleys.com NV.
 */
package com.parleys.api.resource.serializer;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;


import com.parleys.core.domain.Space;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

@Provider
public class SpaceMessageBodyWriter implements MessageBodyWriter<List<Space>> {

  @Override
  public long getSize(List<Space> arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
    return -1;
  }

  @Override
  public boolean isWriteable(Class<?> claz, Type type, Annotation[] arg2, MediaType arg3) {
    // Type genericType =((ParameterizedType) type).getActualTypeArguments()[0];
     return List.class.isAssignableFrom(claz) && MediaType.APPLICATION_ATOM_XML_TYPE.equals(arg3); // && Space.class.equals(genericType);
  }

  @Override
  public void writeTo(List<Space> spaces, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream outputStream)
      throws IOException, WebApplicationException {
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType("atom_1.0");
    feed.setEncoding("UTF-8");
    feed.setTitle("Test");
    feed.setDescription("blablabla");
    
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
      
    SyndEntry entry;
    // SyndContent description;
    // StringBuilder stringBuilder = new StringBuilder();
    for (Space space : spaces){
      // stringBuilder.append(space.getName()).append('\n');
      entry = new SyndEntryImpl();
      
      entry.setTitle(space.getName());
      entries.add(entry);
    }
    feed.setEntries(entries);
    SyndFeedOutput output = new SyndFeedOutput();
    
    try {
      outputStream.write(output.outputString(feed).getBytes());
    }
    catch (FeedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

}
